package com.future.mayi.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.baselib.utils.ToastUtil;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.dialog.KefuDialog;
import com.future.mayi.model.GoodsItemModel;
import com.future.mayi.model.ReturnGoodsModel;
import com.future.mayi.model.interfaces.ListImgListener;
import com.future.mayi.qsale.utils.SelectImgUtils;
import com.future.mayi.utils.CompressImgUtils;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.HtmlFormat;
import com.future.mayi.utils.PriceUtils;
import com.future.mayi.utils.UploadListImgUtils;
import com.future.mayi.widget.ListImgView;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.imnjh.imagepicker.activity.PhotoPickerActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ApplyRefundActivity extends BaseTitleActivity implements ListImgListener {
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    @BindView(R.id.edt_info)
    EditText edtInfo;
    @BindView(R.id.list_img)
    ListImgView listImg;
    @BindView(R.id.tv_add_reason)
    TextView tvAddReason;
    @BindView(R.id.tv_reason)
    TextView tvReason;
    @BindView(R.id.ll_server)
    LinearLayout llServer;
    @BindView(R.id.tv_enter)
    TextView tvEnter;
    @BindView(R.id.tv_sub)
    TextView tvSub;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_add)
    TextView tvAdd;


    private String orderId;
    private GoodsItemModel model;
    private double money;

    private String imgUrl;


    public static void startActivity(Context context, String orderId, GoodsItemModel model) {
        Intent intent = new Intent(context, ApplyRefundActivity.class);
        intent.putExtra("orderId", orderId);
        intent.putExtra("appraisal", false);
        intent.putExtra("goodsItemModel", model);
        context.startActivity(intent);
    }


    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("申请退款");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_apply_refund);
    }

    @Override
    protected void initView() {
        orderId = getIntent().getStringExtra("orderId");
        model = (GoodsItemModel) getIntent().getSerializableExtra("goodsItemModel");
        if (model != null) {
            View view = LayoutInflater.from(this).inflate(R.layout.layout_goods_order_goods_item, llGoods, false);
            ImageView ivImg = view.findViewById(R.id.iv_img);
            TextView tvGoodsTitle = view.findViewById(R.id.tv_title);
            TextView tvGoodsPrice = view.findViewById(R.id.tv_goods_price);
            TextView tvValue = view.findViewById(R.id.tv_value);
            TextView tvRefundStatus = view.findViewById(R.id.tv_refund);
            View viewLine = view.findViewById(R.id.view_line);
            viewLine.setVisibility(View.GONE);
            HCUtils.loadWebImg(this, ivImg, model.getMain_img());
            tvGoodsTitle.setText(model.getGoods_name());
            tvValue.setText(model.getGoods_attr() + ",x" + (model.getBuy_num()));
            tvGoodsPrice.setText(PriceUtils.getPriceText2(model.getUnit_price()));
            llGoods.addView(view);
            tvNum.setText(String.valueOf(model.getBuy_num()));
            getReturnPrice();
        }

    }

    @Override
    protected void initDates() {

        getRefundDescList();
    }

    @Override
    protected void initListener() {
        listImg.setListener(this);
    }


    private SelectImgUtils selectImgUtils;

    @Override
    public void onClickAddImg(int maxSelectNum) {
        if (selectImgUtils == null) {
            selectImgUtils = new SelectImgUtils();
        }
        selectImgUtils.selectImg(ApplyRefundActivity.this, maxSelectNum);
    }

    @Override
    public void onClickDeleteImg(int position) {

    }

    @Override
    public void onClickImg(int position) {

    }


    private void enter() {
        tvEnter.setEnabled(false);
        if (TextUtils.isEmpty(tvReason.getText())) {
            toast("请选择退款原因！");
            tvEnter.setEnabled(true);
            return;
        }

        showLoadingDialog();
        String reason = tvReason.getText().toString();
        List<String> img = listImg.getImgString();

        if (img != null && img.size() > 0 && TextUtils.isEmpty(imgUrl)) {
            uploadImg(img);
            return;
        }


        List<ReturnGoodsModel> list = new ArrayList<>(1);
        ReturnGoodsModel returnGoodsModel = new ReturnGoodsModel();
        returnGoodsModel.setNum(Integer.valueOf(tvNum.getText().toString()));
        returnGoodsModel.setOrder_goods_id(model.getOrder_goods_id());
        list.add(returnGoodsModel);
        String refund_explain = TextUtils.isEmpty(edtInfo.getText()) ? "" : edtInfo.getText().toString();
        new HttpRequest<DefaultResponse>()
                .with(this).setApiCode(ApiCst.refundOrder)
                .addParam("token", App.getToken(mContext))
                .addParam("order_id", orderId)
                .addParam("return_desc", reason)
                .addParam("return_explain", refund_explain)
                .addParam("return_img", img == null ? "" : imgUrl)
                .addParam("return_goods", App.getGson().toJson(list))
//                .addParam("type",)
//                .addParam("return_price",)
//                .addParam("is_all_order",)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        dissmissLoadingDialog();
                        toast(response.message);
                        finish();
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        toast(message);
                        dissmissLoadingDialog();
                        tvEnter.setEnabled(true);
                    }
                }).start(new DefaultResponse());

    }

    private void getReturnPrice(){
        showLoadingDialog();
        List<ReturnGoodsModel> list = new ArrayList<>(1);
        ReturnGoodsModel returnGoodsModel = new ReturnGoodsModel();
        returnGoodsModel.setNum(Integer.valueOf(tvNum.getText().toString()));
        returnGoodsModel.setOrder_goods_id(model.getOrder_goods_id());
        list.add(returnGoodsModel);
        new HttpRequest<DefaultResponse>()
                .with(this).setApiCode(ApiCst.getReturnPirce)
                .addParam("token", App.getToken(mContext))
                .addParam("order_id", orderId)
                .addParam("return_goods",  App.getGson().toJson(list))
//                .addParam("is_all_order", 0)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        dissmissLoadingDialog();
                        if (!TextUtils.isEmpty(response.content)) {
                            JSONObject object = null;
                            try {
                                object = new JSONObject(response.content);
                                money = object.optDouble("total_return_price",0.0d);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        tvPrice.setText("退款金额    ¥".concat(PriceUtils.getPriceText2(money)));
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        toast(message);
                        dissmissLoadingDialog();
                    }
                }).start(new DefaultResponse());

    }

    private void uploadImg(List<String> img) {
        UploadListImgUtils uploadListImgUtils = new UploadListImgUtils(this, new UploadListImgUtils.UploadListener() {
            @Override
            public void uploadSucceed(String imgString) {
                imgUrl = imgString;
                enter();
            }

            @Override
            public void uploadFailed(String message) {
                dissmissLoadingDialog();
                toast(message);
            }
        });
        uploadListImgUtils.startUpload(img);
    }


    private List<String> reasonList;
    private OptionsPickerView reasonDialog;

    private void selectReason() {
        if (reasonList == null) {
            getRefundDescList();
            toast("正在获取退款原因列表");
            return;
        }
        if (reasonDialog == null) return;
        reasonDialog.show();
    }

    public void getRefundDescList() {
        new HttpRequest<DefaultResponse>()
                .with(this).setApiCode(ApiCst.getRefundDescList)
                .addParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        if (TextUtils.isEmpty(response.content)) return;
                        reasonList = App.getGson().fromJson(response.content, new TypeToken<List<String>>() {
                        }.getType());
                        if (reasonList == null) reasonList = new ArrayList<>();
                        if (reasonDialog == null) {
                            reasonDialog = new OptionsPickerView.Builder(ApplyRefundActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
                                @Override
                                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                                    dissmissLoadingDialog();
                                    tvReason.setText(reasonList.get(options1));
                                }
                            }).setCancelColor(getResources().getColor(R.color.main_text_color))
                                    .setSubmitColor(getResources().getColor(R.color.main_color))
                                    .setContentTextSize(17)
                                    .setTitleText("请选择退款原因")
                                    .build();
                        }
                        reasonDialog.setPicker(reasonList);
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        toast(message);
                    }
                }).start(new DefaultResponse());

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == SelectImgUtils.REQUEST_CODE_IMAGE) {
            final ArrayList<String> pathList = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
            if (pathList != null && pathList.size() > 0 && (!TextUtils.isEmpty(pathList.get(0)))) {
                showLoadingDialog();
                CompressImgUtils compressImgUtils = new CompressImgUtils();
                compressImgUtils.compressImg(pathList, new CompressImgUtils.OnCompressImgListener() {
                    @Override
                    public void onSucceed(List<String> pathList) {
                        dissmissLoadingDialog();
                        listImg.addImg(pathList);
                    }

                    @Override
                    public void onFailed(Exception e) {
                        dissmissLoadingDialog();
                    }
                });
            }
        }
    }


    @OnClick({R.id.tv_sub, R.id.tv_add, R.id.tv_add_reason, R.id.ll_server, R.id.tv_enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_sub: {
                if (TextUtils.isEmpty(tvNum.getText())) {
                    tvNum.setText("1");
                    money = PriceUtils.getMultiply(1, model.getUnit_price());
                    tvPrice.setText("退款金额    ¥".concat(PriceUtils.getPriceText2(money)));
                    return;
                }
                int num = Integer.valueOf(tvNum.getText().toString()) - 1;
                if (num <= 0) num = 1;
                tvNum.setText(String.valueOf(num));
                getReturnPrice();
            }
            break;
            case R.id.tv_add: {
                if (TextUtils.isEmpty(tvNum.getText())) {
                    tvNum.setText("1");
                    money = PriceUtils.getMultiply(1, model.getUnit_price());
                    tvPrice.setText("退款金额    ¥".concat(PriceUtils.getPriceText2(money)));
                    return;
                }
                int num = Integer.valueOf(tvNum.getText().toString()) + 1;
                int max = model == null ? 1 : model.getBuy_num();
                if (num > max) {
                    ToastUtil.getInstance().show(getActivity(), "数量超出范围");
                    return;
                }
                if (num <= 0) num = 0;
                tvNum.setText(String.valueOf(num));
                getReturnPrice();
            }
            break;
            case R.id.tv_add_reason:
                selectReason();
                break;
            case R.id.ll_server:
                new KefuDialog(this).show(1);
                break;
            case R.id.tv_enter:
                imgUrl = null;
                enter();
                break;
        }
    }


}
